<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>十大常见排序算法 | 飞の博客</title><meta name="author" content="Fei"><meta name="copyright" content="Fei"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="十大常见排序算法，Java语言实现">
<meta property="og:type" content="article">
<meta property="og:title" content="十大常见排序算法">
<meta property="og:url" content="https://tengfei2233.gitee.io/2022/11/23/%E5%8D%81%E5%A4%A7%E5%B8%B8%E8%A7%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="飞の博客">
<meta property="og:description" content="十大常见排序算法，Java语言实现">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-1/sort-algorithm.jpg">
<meta property="article:published_time" content="2022-11-23T02:21:27.000Z">
<meta property="article:modified_time" content="2022-11-23T02:21:27.000Z">
<meta property="article:author" content="Fei">
<meta property="article:tag" content="排序算法">
<meta property="article:tag" content="冒泡排序">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-1/sort-algorithm.jpg"><link rel="shortcut icon" href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/icon.png"><link rel="canonical" href="https://tengfei2233.gitee.io/2022/11/23/%E5%8D%81%E5%A4%A7%E5%B8%B8%E8%A7%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="msvalidate.01" content="2ADFA30867CBC6E090E3C5B244DC311D"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.3.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?07a1f58fb95d3d4a97c2ae0a181c9964";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '十大常见排序算法',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-23 10:21:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-1/sort-algorithm.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="飞の博客"><span class="site-name">飞の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">十大常见排序算法</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-23T02:21:27.000Z" title="发表于 2022-11-23 10:21:27">2022-11-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-23T02:21:27.000Z" title="更新于 2022-11-23 10:21:27">2022-11-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%AE%97%E6%B3%95/">算法</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%AE%97%E6%B3%95/%E6%8E%92%E5%BA%8F/">排序</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="十大常见排序算法"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="十大常见排序算法"><a href="#十大常见排序算法" class="headerlink" title="十大常见排序算法"></a>十大常见排序算法</h2><h3 id="差异比较"><a href="#差异比较" class="headerlink" title="差异比较"></a>差异比较</h3><table>
<thead>
<tr>
<th align="center">排序方法</th>
<th align="center">时间复杂度(平均)</th>
<th align="center">时间复杂度(最好)</th>
<th align="center">时间复杂度(最坏)</th>
<th align="center">空间复杂度</th>
<th align="center">稳定性</th>
</tr>
</thead>
<tbody><tr>
<td align="center">冒泡排序</td>
<td align="center">O(n²)</td>
<td align="center">O(n)</td>
<td align="center">O(n²)</td>
<td align="center">O(1)</td>
<td align="center">稳定</td>
</tr>
<tr>
<td align="center">快速排序</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(n²)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">不稳定</td>
</tr>
<tr>
<td align="center">插入排序</td>
<td align="center">O(n²)</td>
<td align="center">O(n)</td>
<td align="center">O(n²)</td>
<td align="center">O(1)</td>
<td align="center">稳定</td>
</tr>
<tr>
<td align="center">选择排序</td>
<td align="center">O(n²)</td>
<td align="center">O(n²)</td>
<td align="center">O(n²)</td>
<td align="center">O(1)</td>
<td align="center">不稳定</td>
</tr>
<tr>
<td align="center">希尔排序</td>
<td align="center">O(n¹˙³)</td>
<td align="center">O(n)</td>
<td align="center">O(n²)</td>
<td align="center">O(1)</td>
<td align="center">不稳定</td>
</tr>
<tr>
<td align="center">堆排序</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(1)</td>
<td align="center">不稳定</td>
</tr>
<tr>
<td align="center">归并排序</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(nlog₂n)</td>
<td align="center">O(n)</td>
<td align="center">稳定</td>
</tr>
<tr>
<td align="center">桶排序</td>
<td align="center">O(n+k)</td>
<td align="center">O(n)</td>
<td align="center">O(n²)</td>
<td align="center">O(n+k)</td>
<td align="center">稳定</td>
</tr>
<tr>
<td align="center">基数排序</td>
<td align="center">O(n*k)</td>
<td align="center">O(n*k)</td>
<td align="center">O(n*k)</td>
<td align="center">O(n+k)</td>
<td align="center">稳定</td>
</tr>
<tr>
<td align="center">计数排序</td>
<td align="center">O(n+k)</td>
<td align="center">O(n+k)</td>
<td align="center">O(n+k)</td>
<td align="center">O(n+k)</td>
<td align="center">稳定</td>
</tr>
</tbody></table>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><h4 id="一、冒泡排序"><a href="#一、冒泡排序" class="headerlink" title="一、冒泡排序"></a>一、冒泡排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 冒泡排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">bubbleSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length - <span class="number">1</span>; i++) &#123;</span><br><span class="line">        <span class="comment">// 标志位</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">0</span>; j &lt; arr.length - i - <span class="number">1</span>; j++) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">temp</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">if</span> (arr[j] &gt; arr[j + <span class="number">1</span>]) &#123;</span><br><span class="line">                flag = <span class="literal">true</span>;</span><br><span class="line">                temp = arr[j];</span><br><span class="line">                arr[j] = arr[j + <span class="number">1</span>];</span><br><span class="line">                arr[j + <span class="number">1</span>] = temp;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 一次未发生比较，直接终止</span></span><br><span class="line">        <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="二、快速排序"><a href="#二、快速排序" class="headerlink" title="二、快速排序"></a>二、快速排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 快速排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr   数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> begin 快排开始位</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> end   快排结束位</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">quickSort</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> begin, <span class="type">int</span> end)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (begin &lt; end) &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">key</span> <span class="operator">=</span> arr[begin];</span><br><span class="line">        <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> begin, j = end;</span><br><span class="line">        <span class="keyword">while</span> (i &lt; j) &#123;</span><br><span class="line">            <span class="comment">// 左指针右移</span></span><br><span class="line">            <span class="keyword">while</span> (i &lt; j &amp;&amp; arr[j] &gt;= key) &#123;</span><br><span class="line">                j--;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 先用右边的替换左边的，反正右边的的值已经赋值给key了</span></span><br><span class="line">            <span class="keyword">if</span> (i &lt; j) &#123;</span><br><span class="line">                arr[i] = arr[j];</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 右指针左移</span></span><br><span class="line">            <span class="keyword">while</span> (i &lt; j &amp;&amp; arr[i] &lt;= key) &#123;</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 再用左边的替换右边的，邮编的值为小于key的值</span></span><br><span class="line">            <span class="keyword">if</span> (i &lt; j) &#123;</span><br><span class="line">                arr[j] = arr[i];</span><br><span class="line">                j--;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 替换左指针位置为key</span></span><br><span class="line">            arr[i] = key;</span><br><span class="line">            <span class="comment">// 递归，分而治之</span></span><br><span class="line">            quickSort(arr, begin, i - <span class="number">1</span>);</span><br><span class="line">            quickSort(arr, i + <span class="number">1</span>, end);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="三、插入排序"><a href="#三、插入排序" class="headerlink" title="三、插入排序"></a>三、插入排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 插入排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排序数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">insertSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    <span class="type">int</span> i, j, k;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">1</span>; i &lt; len; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (j = i - <span class="number">1</span>; j &gt;= <span class="number">0</span>; j--) &#123;</span><br><span class="line">            <span class="keyword">if</span> (arr[j] &gt; arr[i]) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (j != i - <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">temp</span> <span class="operator">=</span> arr[i];</span><br><span class="line">            <span class="keyword">for</span> (k = i - <span class="number">1</span>; k &gt; j; k--) &#123;</span><br><span class="line">                arr[k + <span class="number">1</span>] = arr[k];</span><br><span class="line">            &#125;</span><br><span class="line">            arr[k + <span class="number">1</span>] = temp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="四、希尔排序"><a href="#四、希尔排序" class="headerlink" title="四、希尔排序"></a>四、希尔排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 希尔排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">shellSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    <span class="type">int</span> temp;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">step</span> <span class="operator">=</span> len / <span class="number">2</span>; step &gt;= <span class="number">1</span>; step /= <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> step; i &lt; len; i++) &#123;</span><br><span class="line">            temp = arr[i];</span><br><span class="line">            <span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> i - step;</span><br><span class="line">            <span class="keyword">while</span> (j &gt;= <span class="number">0</span> &amp;&amp; arr[j] &gt; temp) &#123;</span><br><span class="line">                arr[j + step] = arr[j];</span><br><span class="line">                j -= step;</span><br><span class="line">            &#125;</span><br><span class="line">            arr[j + step] = temp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="五、选择排序"><a href="#五、选择排序" class="headerlink" title="五、选择排序"></a>五、选择排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 选择排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">selectSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="comment">// i:有序区末尾位置,j:无序区开始位置,min:无序区最小元素位置</span></span><br><span class="line">    <span class="type">int</span> i, j, min;</span><br><span class="line">    <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        min = i;</span><br><span class="line">        <span class="comment">// 找出arr[i+1]-arr[len-1]中最小元素</span></span><br><span class="line">        <span class="keyword">for</span> (j = i + <span class="number">1</span>; j &lt; len; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (arr[j] &lt; arr[min]) &#123;</span><br><span class="line">                min = j;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 若min!=i则说明找到了最下的元素，进行交换，保证arr[0]-arr[i]之间有序</span></span><br><span class="line">        <span class="keyword">if</span> (min != i) &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">temp</span> <span class="operator">=</span> arr[i];</span><br><span class="line">            arr[i] = arr[min];</span><br><span class="line">            arr[min] = temp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="六、堆排序"><a href="#六、堆排序" class="headerlink" title="六、堆排序"></a>六、堆排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> 	* 堆排序</span></span><br><span class="line"><span class="comment"> 	*</span></span><br><span class="line"><span class="comment"> 	* <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment"> 	*/</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">heapSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="type">int</span> i, temp, len = arr.length;</span><br><span class="line">    <span class="comment">// 从2/n-1到0依次遍历，遍历之后，得到的数组实际上是一个最大二叉堆</span></span><br><span class="line">    <span class="keyword">for</span> (i = len / <span class="number">2</span> - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        maxHeapDown(arr, i, len - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 从最后一个元素开始对序列进行调整，不断缩小调整的范围直到第一个元素</span></span><br><span class="line">    <span class="keyword">for</span> (i = len - <span class="number">1</span>; i &gt; <span class="number">0</span>; i--) &#123;</span><br><span class="line">        <span class="comment">// 交换arr[0]和arr[i]。交换后，arr[i]是arr[0...i]中最大值。</span></span><br><span class="line">        temp = arr[<span class="number">0</span>];</span><br><span class="line">        arr[<span class="number">0</span>] = arr[i];</span><br><span class="line">        arr[i] = temp;</span><br><span class="line">        <span class="comment">// 调整arr[0...i-1]，使得arr[0...i-1]任然是一个最大堆。</span></span><br><span class="line">        maxHeapDown(arr, <span class="number">0</span>, i - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 最大堆的向下调整算法</span></span><br><span class="line"><span class="comment">     * 数组实现的堆中，第N个节点的左孩子是2*N+1，右孩子是2*N+2</span></span><br><span class="line"><span class="comment">     * 其中N为数组下标的索引值，数组中第一个数的N对应的值为0</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr   待排数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> start 被下调节点的起始位置(一般为0，表示从第一个开始)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> end   截至范围，一般为数组中最后一个元素的索引</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">maxHeapDown</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> start, <span class="type">int</span> end)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">c</span> <span class="operator">=</span> start, l = <span class="number">2</span> * c + <span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span> <span class="variable">temp</span> <span class="operator">=</span> arr[c];</span><br><span class="line">    <span class="keyword">for</span> (; l &lt;= end; c = l, l = <span class="number">2</span> * l + <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="comment">// l是左孩子，l+1是右孩子</span></span><br><span class="line">        <span class="keyword">if</span> (l &lt; end &amp;&amp; arr[l] &lt; arr[l + <span class="number">1</span>]) &#123;</span><br><span class="line">            l++;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (temp &gt;= arr[l]) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            arr[c] = arr[l];</span><br><span class="line">            arr[l] = temp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="七、-归并排序"><a href="#七、-归并排序" class="headerlink" title="七、 归并排序"></a>七、 归并排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 归并排序，从上往下</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr   待排数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> start 起始位置</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> end   结束位置（len-1）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">mergeSortUp2Down</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> start, <span class="type">int</span> end)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span> || start &gt;= end) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> <span class="variable">mid</span> <span class="operator">=</span> (start + end) / <span class="number">2</span>;</span><br><span class="line">    <span class="comment">// 递归排序前半部分</span></span><br><span class="line">    mergeSortUp2Down(arr, start, mid);</span><br><span class="line">    <span class="comment">// 递归排序后半部分</span></span><br><span class="line">    mergeSortUp2Down(arr, mid + <span class="number">1</span>, end);</span><br><span class="line">    <span class="comment">// a[start...mid] 和 a[mid...end]是两个有序空间，</span></span><br><span class="line">    <span class="comment">// 将它们排序成一个有序空间a[start...end]</span></span><br><span class="line">    merge(arr, start, mid, end);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 归并排序，从下往上</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">mergeSortDown2Up</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; len; i *= <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="type">int</span> j;</span><br><span class="line">        <span class="comment">// 将&quot;每2个相邻的子数组&quot; 进行合并排序。</span></span><br><span class="line">        <span class="keyword">for</span> (j = <span class="number">0</span>; j + <span class="number">2</span> * i - <span class="number">1</span> &lt; len; j += (<span class="number">2</span> * i))</span><br><span class="line">            merge(arr, j, j + i - <span class="number">1</span>, j + <span class="number">2</span> * i - <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 若 i+gap-1 &lt; len-1，则剩余一个子数组没有配对。</span></span><br><span class="line">        <span class="comment">// 将该子数组合并到已排序的数组中。</span></span><br><span class="line">        <span class="keyword">if</span> (j + i - <span class="number">1</span> &lt; len - <span class="number">1</span>)</span><br><span class="line">            merge(arr, j, j + i - <span class="number">1</span>, len - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将一个数组中两个相邻区域合并成一个</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr   待排数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> start 第一个数组的起始位置</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> mid   第一个数组的结束位置，也是第二个数组的开始位置</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> end   第二个数组的结束位置</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">merge</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> start, <span class="type">int</span> mid, <span class="type">int</span> end)</span> &#123;</span><br><span class="line">    <span class="comment">// 汇总两个数组的临时区域</span></span><br><span class="line">    <span class="type">int</span>[] temp = <span class="keyword">new</span> <span class="title class_">int</span>[end - start + <span class="number">1</span>];</span><br><span class="line">    <span class="comment">// 第一个有序区索引，第二个有序区索引，临时区索引</span></span><br><span class="line">    <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> start, j = mid + <span class="number">1</span>, k = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (i &lt;= mid &amp;&amp; j &lt;= end) &#123;</span><br><span class="line">        <span class="keyword">if</span> (arr[i] &lt; arr[j]) &#123;</span><br><span class="line">            temp[k++] = arr[i++];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            temp[k++] = arr[j++];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (i &lt;= mid) &#123;</span><br><span class="line">        temp[k++] = arr[i++];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (j &lt;= end) &#123;</span><br><span class="line">        temp[k++] = arr[j++];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 将排好序的数组全部整合到数组a中</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; k; i++) &#123;</span><br><span class="line">        arr[start + i] = temp[i];</span><br><span class="line">    &#125;</span><br><span class="line">    temp = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="八、桶排序"><a href="#八、桶排序" class="headerlink" title="八、桶排序"></a>八、桶排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 桶排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">bucketSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> <span class="variable">max</span> <span class="operator">=</span> arr[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (arr[i] &gt; max) &#123;</span><br><span class="line">            max = arr[i];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    max++;</span><br><span class="line">    <span class="keyword">if</span> (max &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 存储数据的桶，桶容量为待排数组中的最大值</span></span><br><span class="line">    <span class="type">int</span>[] buckets = <span class="keyword">new</span> <span class="title class_">int</span>[max];</span><br><span class="line">    <span class="comment">// 计数</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        buckets[arr[i]]++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 排序</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>, j = <span class="number">0</span>; i &lt; max; i++) &#123;</span><br><span class="line">        <span class="keyword">while</span> (buckets[i]-- &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            arr[j++] = i;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    buckets = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="九、基数排序"><a href="#九、基数排序" class="headerlink" title="九、基数排序"></a>九、基数排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 基数排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">radixSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> <span class="variable">max</span> <span class="operator">=</span> arr[<span class="number">0</span>], len = arr.length;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (arr[i] &gt; max) &#123;</span><br><span class="line">            max = arr[i];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 指数，当exp=1时按个位排序，当exp=10时按十位排序，当exp=100时按百位排序</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">exp</span> <span class="operator">=</span> <span class="number">1</span>; max / exp &gt; <span class="number">0</span>; exp *= <span class="number">10</span>) &#123;</span><br><span class="line">        countSort(arr, exp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">countSort</span><span class="params">(<span class="type">int</span>[] arr, <span class="type">int</span> exp)</span> &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> arr.length;</span><br><span class="line">    <span class="comment">// 存储被排序数组的临时数组</span></span><br><span class="line">    <span class="type">int</span>[] outputs = <span class="keyword">new</span> <span class="title class_">int</span>[len];</span><br><span class="line">    <span class="type">int</span>[] buckets = <span class="keyword">new</span> <span class="title class_">int</span>[<span class="number">10</span>];</span><br><span class="line">    <span class="comment">// 将数据出现的次数存储再bucket中</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        buckets[(arr[i] / exp) % <span class="number">10</span>]++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 更改buckets[i]，目的是让更改后的值是改数据再putput[]中的值</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">        buckets[i] += buckets[i - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 将数组存储到临时数据outputs中</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> len - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        outputs[buckets[(arr[i] / exp) % <span class="number">10</span>] - <span class="number">1</span>] = arr[i];</span><br><span class="line">        buckets[(arr[i] / exp) % <span class="number">10</span>]--;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 见排序好的数组赋值给arr</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        arr[i] = outputs[i];</span><br><span class="line">    &#125;</span><br><span class="line">    outputs = <span class="literal">null</span>;</span><br><span class="line">    buckets = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="十、计数排序"><a href="#十、计数排序" class="headerlink" title="十、计数排序"></a>十、计数排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 计数排序</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> arr 待排数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">countSort</span><span class="params">(<span class="type">int</span>[] arr)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 求出arr中数据的差值</span></span><br><span class="line">    <span class="type">int</span> <span class="variable">max</span> <span class="operator">=</span> arr[<span class="number">0</span>], len = arr.length;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (arr[i] &gt; max) &#123;</span><br><span class="line">            max = arr[i];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    max = max + <span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span>[] res = <span class="keyword">new</span> <span class="title class_">int</span>[len];</span><br><span class="line">    <span class="comment">// 桶数组</span></span><br><span class="line">    <span class="type">int</span>[] buckets = <span class="keyword">new</span> <span class="title class_">int</span>[max];</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        buckets[arr[i]]++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt; max; i++) &#123;</span><br><span class="line">        buckets[i] += buckets[i - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> len - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">a</span> <span class="operator">=</span> arr[i];</span><br><span class="line">        res[buckets[a] - <span class="number">1</span>] = a;</span><br><span class="line">        buckets[a] -= <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; len; i++) &#123;</span><br><span class="line">        arr[i] = res[i];</span><br><span class="line">    &#125;</span><br><span class="line">    res = <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io">Fei</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io/2022/11/23/%E5%8D%81%E5%A4%A7%E5%B8%B8%E8%A7%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/">https://tengfei2233.gitee.io/2022/11/23/%E5%8D%81%E5%A4%A7%E5%B8%B8%E8%A7%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://tengfei2233.gitee.io" target="_blank">飞の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/">排序算法</a><a class="post-meta__tags" href="/tags/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F/">冒泡排序</a></div><div class="post_share"><div class="social-share" data-image="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-1/sort-algorithm.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/11/17/FastJson%E5%92%8CFastJson2%E5%BA%8F%E5%88%97%E5%8C%96Redis%E9%85%8D%E7%BD%AE/" title="FastJson和FastJson2序列化Redis配置"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/post_default_cover.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">FastJson和FastJson2序列化Redis配置</div></div></a></div><div class="next-post pull-right"><a href="/2022/12/2/%E6%9F%90%E5%85%AC%E5%8F%B8%E7%A7%8B%E6%8B%9B%E6%8A%80%E6%9C%AF%E4%B8%80%E9%9D%A2%E9%A2%98%E7%9B%AE%E5%88%86%E4%BA%AB/" title="某公司秋招技术一面题目分享"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/post_default_cover.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">某公司秋招技术一面题目分享</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Fei</div><div class="author-info__description">当你想起来了，那就记录一点吧</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/tengfei2233" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://gitee.com/tengfei2233" target="_blank" title="Gitee"><i class="fab fa-git"></i></a><a class="social-icon" href="/youfeige@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">当你迷茫的时候，那就静下心想想吧！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%81%E5%A4%A7%E5%B8%B8%E8%A7%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">十大常见排序算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B7%AE%E5%BC%82%E6%AF%94%E8%BE%83"><span class="toc-number">1.1.</span> <span class="toc-text">差异比较</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.2.</span> <span class="toc-text">代码实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.1.</span> <span class="toc-text">一、冒泡排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.2.</span> <span class="toc-text">二、快速排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.3.</span> <span class="toc-text">三、插入排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.4.</span> <span class="toc-text">四、希尔排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.5.</span> <span class="toc-text">五、选择排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%A0%86%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.6.</span> <span class="toc-text">六、堆排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%83%E3%80%81-%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.7.</span> <span class="toc-text">七、 归并排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E6%A1%B6%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.8.</span> <span class="toc-text">八、桶排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B9%9D%E3%80%81%E5%9F%BA%E6%95%B0%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.9.</span> <span class="toc-text">九、基数排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%81%E3%80%81%E8%AE%A1%E6%95%B0%E6%8E%92%E5%BA%8F"><span class="toc-number">1.2.10.</span> <span class="toc-text">十、计数排序</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="netty的基本使用，基本原理分析，相关问题解(更新中...)"/></a><div class="content"><a class="title" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)">netty的基本使用，基本原理分析，相关问题解(更新中...)</a><time datetime="2023-11-21T09:27:51.000Z" title="发表于 2023-11-21 17:27:51">2023-11-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在conda环境下运行stable-diffusion-webui AI绘图"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图">在conda环境下运行stable-diffusion-webui AI绘图</a><time datetime="2023-11-10T07:30:51.000Z" title="发表于 2023-11-10 15:30:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)">在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)</a><time datetime="2023-11-10T07:27:51.000Z" title="发表于 2023-11-10 15:27:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Docker Compose学习"/></a><div class="content"><a class="title" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习">Docker Compose学习</a><time datetime="2023-08-27T15:34:50.000Z" title="发表于 2023-08-27 23:34:50">2023-08-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Dockerfile学习"/></a><div class="content"><a class="title" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习">Dockerfile学习</a><time datetime="2023-08-27T15:34:37.000Z" title="发表于 2023-08-27 23:34:37">2023-08-27</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-1/sort-algorithm.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2024 By Fei</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">欢迎进入<a href="tengfei2233.gitee.io/">飞の博客</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/utils.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/main.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/tw_cn.min.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.1.1/instantpage.min.js" type="module"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.staticfile.org/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '0kbeJfFlvhvkYfqMqwwVCx1a-gzGzoHsz',
      appKey: 'rziWUw1MTHMW7d9eeCQzu9HV',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.staticfile.org/valine/1.5.1/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/search/local-search.min.js"></script></div></body></html>